package com.jeesite.modules.dataScreen.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeesite.modules.dataScreen.dao.SysMenuDao;
import com.jeesite.modules.dataScreen.entity.SysMenu;
import com.jeesite.modules.dataScreen.exceptions.BgManageException;
import com.jeesite.modules.dataScreen.service.SysMenuService;
import com.jeesite.modules.dataScreen.web.dto.SysMenuDto;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单(SysMenu)表服务实现类
 *
 * @author makejava
 * @since 2024-09-24 15:29:55
 */
@Service("sysMenuService")
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenu> implements SysMenuService {

    @Override
    public List<SysMenu> findAll(String name) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like(SysMenu::getMenuName, name);
        }
        return getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public SysMenu findById(Integer id) {
        return getById(id);
    }

    @Override
    public void updateOrCreate(SysMenuDto dto) {
        SysMenu sysMenu = new SysMenu();
        sysMenu.setId(dto.getId());
        sysMenu.setMenuName(dto.getMenuName());
        sysMenu.setRoutePath(dto.getRoutePath());
        sysMenu.setRemark(dto.getRemark());
        sysMenu.setPermissions(dto.getPermissions());
        if (dto.getId() == null) {
            sysMenu.setCreateAt(new Date());
        }
        sysMenu.setUpdateAt(new Date());
        sysMenu.setDeleted(0);
        saveOrUpdate(sysMenu);
    }


    @Override
    public Map<Integer, String> findRoleHomeUrl(List<Integer> homeUrls) {
        List<SysMenu> sysMenus = getBaseMapper().selectBatchIds(homeUrls);
        return sysMenus.stream().collect(Collectors.toMap(SysMenu::getId, SysMenu::getRoutePath));
    }

    @Override
    public void delete(Integer id) {
        List<String> roleNames = getBaseMapper().findRoleNameByMenuId(id);
        if (CollUtil.isNotEmpty(roleNames)) {
            String format = StrUtil.format("菜单存在角色[{}]绑定", CollUtil.join(roleNames, ","));
            throw BgManageException.newInstance(format);
        }
        removeById(id);
    }
}

